import { createApp } from 'vue'
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import App from './App.vue'
// ant-design-vue 进行按需加载引入
import Antd from './configAntD'
import LegoBricksSea from 'lego-bricks-sea'
import router from './routes/index'
import store from './store/index'
import 'ant-design-vue/dist/antd.less'
import 'lego-bricks-sea/dist/bundle.css'
import 'cropperjs/dist/cropper.css'
import { RespData } from './store/respTypes'
export type ICustomAxiosConfig = AxiosRequestConfig & {
  opName?: string;
}

const app = createApp(App)
console.log('check:', process.env.NODE_ENV)
console.log('foo:', process.env.VUE_APP_FOO)

let baseBackendURL = ''
let baseH5URL = '' 
if (process.env.NODE_ENV === 'development' || process.env.VUE_APP_STAGINE) {
  // 开发环境
  // use test backend aip when
  // 1. in development env
  // 2. in staging env
  baseBackendURL = 'http://114.116.94.125:7002'
  baseH5URL = 'http://114.116.94.125:7002' 
} else {
  // 生产环境
  baseBackendURL = 'http://114.116.100.160:7002'
  baseH5URL = 'http://114.116.100.160:7002' 
}
export {baseBackendURL,baseH5URL}
axios.defaults.baseURL = `${baseBackendURL}/api/`
axios.interceptors.request.use(config => {
  const newConfig = config as ICustomAxiosConfig
  store.commit('setError', { status: false, message: ''})
  store.commit('startLoading', { opName: newConfig.opName })
  return config
})
axios.interceptors.response.use((resp: AxiosResponse<RespData>) => {
  const { config, data } = resp
  const newConfig = config as ICustomAxiosConfig
  store.commit('finishLoading', { opName: newConfig.opName })
  const { errno, message } = data
  if (errno !== 0) {
    store.commit('setError', { status: true, message })
    return Promise.reject(data)
  }
  return resp
}, (e: AxiosError) => {
  const newConfig = e.config as ICustomAxiosConfig
  store.commit('setError', { status: true, message: '服务器错误' })
  store.commit('finishLoading', { opName: newConfig.opName })
  return Promise.reject(e)
})
app.use(Antd).use(LegoBricksSea).use(router).use(store)
app.mount('#app')